package com.fingard.dsp.task;

import java.io.File;
import java.util.ArrayList;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.fingard.FGBiz;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.DSPSet;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;

public class TaskCenter {

	private DSPSet dspSet;
	private ArrayList<ScheduledExecutorService> poolList;
	public TaskCenter(DSPSet pDSPSet){
		dspSet = pDSPSet;
	}
	public void startScheduleTask(){
		try{
			String tmpFileName = dspSet.rootDirPath + File.separator + "config" + File.separator + "ScheduledTask.xml";
			if(FileHelper.existFile(tmpFileName)){
				poolList = new ArrayList<ScheduledExecutorService>();
				String fileTxt = FileHelper.readFileText(tmpFileName, "utf-8");
				XmlTextReader xmlReader = new XmlTextReader(fileTxt);
	            while (xmlReader.read("/config/pool")) {
	            	boolean enable = xmlReader.readedXElement.getAttrValueAsBool("enable");
	            	if(enable){
	            		String poolName = xmlReader.readedXElement.getSingleText("name");
	            		StringBuilder sbLog = new StringBuilder();
	            		sbLog.append("启动-"+poolName);
	            		String sizeVal = xmlReader.readedXElement.getSingleText("poolSize");
	            		int poolSize = 1;
	            		if(StringHelper.hasAnyChar(sizeVal)){
	            			poolSize = Integer.parseInt(sizeVal);
	            		}
	            		//任务组，一组内任务串行运行，多组间并发执行
	            		ArrayList<XElement> groupList = xmlReader.readedXElement.getChildList("group");
	            		if(groupList!=null && groupList.size() > 0){
	            			final int groupSize = groupList.size();
	            			ScheduledExecutorService newPool = Executors.newScheduledThreadPool(poolSize);
		            		for(final XElement gXe : groupList){
		            			String gName = gXe.getSingleText("name");
		            			sbLog.append("-"+gName);
		            			int delaySecs = 120;
		            			XElement xeTimer = gXe.getSingleChild("timer");
		            			if(xeTimer!=null){
		            				String delay = xeTimer.getSingleTextNotNull("delaySecs");
		            				if(StringHelper.hasAnyChar(delay)){
		            					delaySecs = Integer.parseInt(delay);
		            					if(delaySecs <= 0){
		            						delaySecs = 120;
		            					}
		            				}
		            			}
		            			sbLog.append("-delaySecs:"+delaySecs);
		            			final TimerTask task1 = new TimerTask() {
		                            public void run() {
		                            	TaskRunner taskRunner = new TaskRunner(groupSize);
		                            	taskRunner.runTask(gXe);
		                            }
		            			};
		            			newPool.scheduleWithFixedDelay(task1, 5, delaySecs, TimeUnit.SECONDS);//每2分钟执行
		            		}
		            		poolList.add(newPool);
	            		}
	            		FGBiz.startLog.addLog(sbLog.toString());
	            	}
	            }
			}
		}catch(Throwable t){
			FGBiz.startLog.exception("TaskCenter", t);
		}
	}
	
	public String stopScheduleTask(){
		StringBuilder sb = new StringBuilder();
		if(poolList != null && poolList.size() > 0){
			for(ScheduledExecutorService eachPool : poolList){
				try{
					if(eachPool.isShutdown()==false){
						eachPool.shutdown();
					}
	    		}catch(Throwable e){
	    			FGBiz.startLog.exception("TaskCenter.stopScheduleTask", e);
	    			sb.append("关闭系统定时任务出现异常：" + LogHelper.getStackTrace(e)+"\r\n");
	    		}
			}
    		if(sb.length() == 0){
    			sb.append("系统定时任务正常关闭");
    		}
    	}
		return sb.toString();
	}
}
